import React, { useCallback, useState, useEffect } from "react"
import { Field_FormSave, Field_name_id } from "@/components/utils/field.list"
import { FormProps } from "@/components/modal/form.modal"
import { FormRender } from "@whzhuke/antd"
import useForm from "antd/es/form/hooks/useForm"
import { Form, InputNumber, Select, Space, Table, Button, message } from "antd"

import stocksService from "@/services/stocks.service"
import goodsService from "@/services/goods.service"

interface Props {
  values?: any
}

const unitValueMap: Record<string, number> = {
  套: 1,
  件: 2,
  个: 3,
  台: 4
}

const unitLabelMap: Record<number | string, string> = {
  1: "套",
  2: "件",
  3: "个",
  4: "台",
  套: "套",
  件: "件",
  个: "个",
  台: "台"
}

const currencySymbolMap: Record<string | number, string> = {
  USD: "$",
  人民币: "¥",
  RMB: "¥",
  $: "$",
  2: "$",
  1: "¥"
}

interface SelectedGoodsItem {
  key: string
  goodsId: string | number
  goodsName: string
  goodsImage?: string
  stockNums?: number
  unit?: number | string
  marketPrice?: number
  currency?: string
  count?: number
  declareUnit?: number | string
}

export const EditStocks: React.FC<Props & FormProps> = props => {
  const { values, onDone } = props
  const [form] = useForm<any>()
  const [unitOptions, setUnitOptions] = useState<Array<{ label: string; value: any }>>([])
  const [goodsOptions, setGoodsOptions] = useState<
    Array<{
      goodsId: string | number
      goodsName: string
      goodsImage?: string
      stockNums?: number
      unit?: number | string
      marketPrice?: number
      currency?: string
      id?: string | number
      name?: string
      imgPath?: string
    }>
  >([])
  const [selectedGoodsList, setSelectedGoodsList] = useState<SelectedGoodsItem[]>([])

  useEffect(() => {
    goodsService.unitslist({}).then(({ data = [] }) => {
      setUnitOptions(data.map((item: any) => ({ label: item.key, value: unitValueMap[item.value] || item.value })))
    })
  }, [])

  useEffect(() => {
    goodsService.list({ pageNum: 1, pageSize: 500 }).then(({ data }) => {
      const list = Array.isArray(data?.list) ? data.list : Array.isArray(data) ? data : []
      setGoodsOptions(
        list.map((item: any) => ({
          goodsId: item.goodsId ?? item.id,
          goodsName: item.name ?? item.goodsName,
          goodsImage: item.imgPath ?? item.goodsImage,
          stockNums: item.stockNums ?? item.count,
          unit: item.unit,
          marketPrice: item.marketPrice,
          currency: item.currency
        }))
      )
    })
  }, [])

  useEffect(() => {
    if (values?.unit && typeof values.unit === "string" && unitValueMap[values.unit] && unitOptions.length > 0) {
      form.setFieldsValue({ unit: unitValueMap[values.unit] })
    }
  }, [values, unitOptions, form])

  // 处理商品选择
  const handleGoodsSelect = useCallback(
    (goodsId: string | number) => {
      const goodsKey = String(goodsId)
      const selectedGoods = goodsOptions.find(item => String(item.goodsId) === goodsKey)
      if (!selectedGoods) return

      setSelectedGoodsList(prev => {
        if (prev.some(item => item.key === goodsKey)) return prev
        return [
          ...prev,
          {
            key: goodsKey,
            goodsId: selectedGoods.goodsId,
            goodsName: selectedGoods.goodsName,
            goodsImage: selectedGoods.goodsImage,
            stockNums: selectedGoods.stockNums,
            unit: selectedGoods.unit,
            marketPrice: selectedGoods.marketPrice,
            currency: selectedGoods.currency,
            declareUnit: selectedGoods.unit
          }
        ]
      })
      form.setFieldsValue({ goods: undefined })
    },
    [goodsOptions, form]
  )

  // 删除商品
  const handleRemoveGoods = useCallback((key: string) => {
    setSelectedGoodsList(prev => prev.filter(item => item.key !== key))
  }, [])

  // 更新申报数量
  const handleCountChange = useCallback((key: string, count: number | null, maxStock?: number) => {
    if (typeof count === "number" && typeof maxStock === "number" && count > maxStock) {
      message.warning("申报数量不能大于库存数量")
      return
    }
    setSelectedGoodsList(prev => prev.map(item => (item.key === key ? { ...item, count: count ?? undefined } : item)))
  }, [])

  const onFinish = useCallback(
    async data => {
      if (!selectedGoodsList.length) {
        message.warning("请至少选择一个商品")
        return
      }

      // 验证所有商品都已填写申报数量和单位
      const hasInvalidItem = selectedGoodsList.some(item => !item.count || !item.declareUnit)
      if (hasInvalidItem) {
        message.warning("请填写所有商品的申报数量和单位")
        return
      }

      const goodsOptionMap = Object.fromEntries(goodsOptions.filter(option => option.goodsId !== undefined).map(option => [String(option.goodsId), option]))

      const payloadGoods = selectedGoodsList.map(item => {
        const matched = goodsOptionMap[String(item.goodsId)]
        return {
          goodsId: item.goodsId,
          goodsName: item.goodsName,
          count: item.count,
          unit: item.declareUnit,
          price: matched?.marketPrice ?? item.marketPrice,
          goodsImage: matched?.goodsImage ?? item.goodsImage
        }
      })

      const totalCount = selectedGoodsList.reduce((sum, item) => sum + (item.count || 0), 0)
      const [firstUnit] = selectedGoodsList
      const unifiedUnit = selectedGoodsList.every(item => item.declareUnit === firstUnit?.declareUnit) ? firstUnit?.declareUnit : undefined

      const payload: Record<string, any> = {
        ...data,
        goods: payloadGoods,
        count: totalCount || undefined,
        unit: unifiedUnit,
        ...(values?.id ? { id: values.id } : {})
      }

      try {
        await stocksService.inventory(payload)
        onDone?.()
      } catch (error) {
        console.error("提交失败:", error)
      }
    },
    [values, onDone, selectedGoodsList, goodsOptions]
  )

  return (
    <FormRender
      form={form}
      initialValues={
        values
          ? {
              ...values
            }
          : {
              unit: 1
            }
      }
      onFinish={onFinish}
      fieldList={[
        values ? Field_name_id : undefined,
        {
          fieldType: "input",
          formItemConfig: { required: !0, name: "code", label: "合同编号" },
          config: { placeholder: "合同编号" }
        },
        {
          fieldType: "input",
          formItemConfig: { required: !0, name: "name", label: "合同名称" },
          config: { placeholder: "合同名称" }
        },
        {
          fieldType: "diy",
          formItemConfig: { required: !0, name: "goods", label: "商品信息" },
          component: (
            <Select
              placeholder="请选择商品"
              optionLabelProp="data-label"
              value={undefined}
              onChange={handleGoodsSelect}
              dropdownRender={menu => (
                <>
                  <div style={{ display: "flex", padding: "4px 12px", fontWeight: 600, fontSize: 12, color: "#666" }}>
                    <span style={{ flex: 1, textAlign: "left" }}>商品名称</span>
                    <span style={{ width: 120, textAlign: "center" }}>库存数量</span>
                    <span style={{ width: 120, textAlign: "center" }}>单位</span>
                    <span style={{ width: 140, textAlign: "center" }}>市场价</span>
                  </div>
                  <div style={{ borderTop: "1px solid #f0f0f0" }}>{menu}</div>
                </>
              )}
              style={{ width: "100%" }}
              showSearch
              filterOption={(input, option) => {
                const label = option?.["data-label"] || ""
                return String(label).toLowerCase().includes(input.toLowerCase())
              }}
            >
              {goodsOptions
                .filter(item => !selectedGoodsList.find(selected => String(selected.goodsId) === String(item.goodsId)))
                .map(item => (
                  <Select.Option key={item.goodsId} value={item.goodsId} data-label={item.goodsName}>
                    <div style={{ display: "flex", alignItems: "center", padding: "4px 12px", fontSize: 12 }}>
                      <span style={{ flex: 1, textAlign: "left" }}>{item.goodsName || "-"}</span>
                      <span style={{ width: 120, textAlign: "center" }}>{item.stockNums ?? "-"}</span>
                      <span style={{ width: 120, textAlign: "center" }}>{unitLabelMap[item.unit ?? ""] || "-"}</span>
                      <span style={{ width: 140, textAlign: "center" }}>
                        {typeof item.marketPrice === "number" ? `${currencySymbolMap[item.currency ?? ""] || ""}${item.marketPrice}` : "-"}
                      </span>
                    </div>
                  </Select.Option>
                ))}
            </Select>
          )
        },
        {
          fieldType: "diy",
          formItemConfig: { label: "申报信息" },
          component: (
            <div>
              <Table
                dataSource={selectedGoodsList}
                columns={[
                  {
                    title: "商品名称",
                    dataIndex: "goodsName",
                    key: "goodsName",
                    width: 200
                  },
                  {
                    title: "库存数量",
                    dataIndex: "stockNums",
                    key: "stockNums",
                    width: 120,
                    render: (value: number | undefined) => value ?? "-"
                  },
                  {
                    title: "申报数量",
                    dataIndex: "count",
                    key: "count",
                    width: 200,
                    render: (value: number | undefined, record: SelectedGoodsItem) => (
                      <InputNumber
                        placeholder="请输入申报数量"
                        min={0}
                        max={record.stockNums}
                        precision={0}
                        style={{ width: "100%" }}
                        value={value}
                        onChange={val => handleCountChange(record.key, val, record.stockNums)}
                      />
                    )
                  },
                  {
                    title: "申报单位",
                    dataIndex: "declareUnit",
                    key: "declareUnit",
                    width: 200,
                    render: (value: number | string | undefined) => unitLabelMap[value ?? ""] || "-"
                  },
                  {
                    title: "操作",
                    key: "action",
                    width: 100,
                    render: (_: any, record: SelectedGoodsItem) => (
                      <Button type="link" danger onClick={() => handleRemoveGoods(record.key)}>
                        删除
                      </Button>
                    )
                  }
                ]}
                pagination={false}
                size="small"
                locale={{ emptyText: "请在上方选择商品" }}
              />
            </div>
          )
        },
        {
          fieldType: "textArea",
          formItemConfig: { required: !0, name: "userNote", label: "用户备注" },
          config: { placeholder: "用户备注" }
        },
        { ...Field_FormSave, formItemConfig: { wrapperCol: { offset: 8, span: 16 } } }
      ]}
      autoComplete="off"
    />
  )
}
